#include "tagexplorer.h"
#include <QMenu>
#include <iostream>
using namespace std;

tagExplorer::tagExplorer(QWidget *parent)
    : QDialog(parent)
{
    ui.setupUi(this);
//    new QListWidgetItem("Vetti", ui.lstFiles);
//    new QListWidgetItem("Kuppai", ui.lstFiles);

    setAcceptDrops(true);

    whichfile=NULL;
    reListDirs();
    hst = new docHistory();
    ui.txtLocation->setText(tr("/"));

    dowork();
    updatebuttons();

}

tagExplorer::~tagExplorer()
{

}

void tagExplorer::on_btnGo_clicked() {
    dowork();
}

void tagExplorer::reListDirs() {
    ui.lstDirs->clear();
    ui.txtLocation->setFocus();
    linkedlist *lst;
    //printf("\nThis is first call");
    lst=clientgetslashlist(); 
    //printf("\nthis is after");
    ui.lstDirs->setRootIsDecorated(true);
    //ui.lstDirs->setColumnCount(2);
    QTreeWidgetItem *root = new QTreeWidgetItem(ui.lstDirs);
    root->setText(0,tr("/"));
    root->setText(1,tr("/"));
    //ui.lstDirs->setFirstItemColumnSpanned(root, true);
    
    char dir[300];
    char *result;
    char pathsofar[300];
    QTreeWidgetItem *tmpitem;
    QTreeWidgetItem *curparent;
    while (!((lst==NULL) || (lst->isEmpty()))) {
        curparent=root;
        strcpy(pathsofar,"/");
        strcpy(dir,lst->remove());
        result=strtok(dir,"/");
        while (result !=NULL) {
            strcat(pathsofar,result);
            QList<QTreeWidgetItem*> items = ui.lstDirs->findItems(tr(pathsofar), Qt::MatchExactly | Qt::MatchRecursive, 0);
            //printf("\npathsofar: %s", pathsofar);
            if (items.empty()) {
                //printf(" ... not found");
                tmpitem=new QTreeWidgetItem(curparent);
                tmpitem->setText(0,tr(result));
                tmpitem->setText(0,tr(pathsofar));
                tmpitem->setText(1,tr(result));
                tmpitem->setText(1,tr(pathsofar));
        //        ui.lstDirs->setFirstItemColumnSpanned(tmpitem, true);
            } else 
                tmpitem=items.first();
            items.clear();
            curparent=tmpitem;
            result=strtok(NULL,"/");
            strcat(pathsofar,"/");
        }
    }
}

void tagExplorer::updatebuttons() {
    ui.btnBack->setEnabled(hst->isBack());
    ui.btnForward->setEnabled(hst->isForward());
    ui.btnUp->setEnabled((strcmp(hst->getCurrent(),"/")!=0));
}


void tagExplorer::on_btnBack_clicked() {
    if (hst->isBack()) {
        ui.txtLocation->setText(hst->getBack());
        dowork();
    }
}
void tagExplorer::on_btnForward_clicked() {
    if (hst->isForward()) {
        ui.txtLocation->setText(hst->getForward());
        dowork();
    }

}
void tagExplorer::on_btnRefresh_clicked() {
    // Refresh Directory List
   reListDirs();
   // Refresh Files in Current Directory
   dowork();
    
}
void tagExplorer::on_btnUp_clicked(){
       QString st;
       if ((hst!=NULL) && ((hst->getCurrent())!=NULL)) {
           st = hst->getCurrent();
           st.append("/../");
           st=getabsmod((st.toAscii()).data());
           if (st.length()==0)
           st=QString("/");
           ui.txtLocation->setText(st);
           dowork();
       }    
}


void tagExplorer::dowork() {

    if ((ui.txtLocation->text()).length()==0)
        return;
   
    hst->add(ui.txtLocation->text().toAscii().data());
    updatebuttons();
    timetaken = QTime(0,0);
    timetaken.restart();
    QString qst;
    int count;
    qst.fromAscii("Query:");
    linkedlist *fileslist;
    ui.lstFiles->clear();
    fileslist=clientlistfiles(ui.txtLocation->text().toAscii().data());
    count=0;
    if (fileslist!=NULL)
    count=fileslist->count();
    while(! ( ( fileslist!=NULL)  && (fileslist->isEmpty())))
        new QListWidgetItem(QIcon(QString::fromUtf8(":Icons/images/Folder.png")),fileslist->remove(), ui.lstFiles);
   
    QString qst1,qst2;
    qst1=QString::fromAscii("Files Found : ");
    qst2.setNum(count,10);
    qst1.append(qst2);
    ui.lblStatus->setText(qst1);
    qst2.setNum(timetaken.elapsed(),10); 
    qst1=QString::fromAscii("Time Taken : ");  
    qst1.append(qst2);
    qst1.append(QString(" msec(s)"));
    ui.lblTime->setText(qst1);
    QList<QTreeWidgetItem*> items = ui.lstDirs->findItems(ui.txtLocation->text(), Qt::MatchExactly | Qt::MatchRecursive,1);
    if(!items.isEmpty()) ui.lstDirs->setCurrentItem(items.first()); // Make the item visible
    items.clear();    
}

void tagExplorer::on_lstFiles_customContextMenuRequested(QPoint p) {
//    QPoint pos=QPoint(ui.lstFiles->pos());
    selectlist = new linkedlist();
    QList<QListWidgetItem*> sel=ui.lstFiles->selectedItems();
    // no Context Sensitive menu if no item is selected
    if (sel.empty())
        return;

    QList<QListWidgetItem*>::iterator it;
    for(it=sel.begin();it!=sel.end();++it)
        selectlist->add((*it)->text().toAscii().data());
    QMenu *context= new QMenu(this);

    if (sel.count()==1)   {       
        char *st=strdup(selectlist->remove());
        selectlist->add(st);
        if (whichfile!=NULL)
            free(whichfile);
        whichfile=strdup(st);
        context->addAction("&Open", this, SLOT( runfile () ) );
    }
    context->addAction("&Tag", this, SLOT( tag()));
    context->addAction("&Copy To", this, SLOT( copyto()));
    context->addAction("&Move To", this, SLOT( moveto()));
    context->popup(QCursor::pos(),0);
}
/*
#include "tagexplorer.h"
#include <QMenu>
#include <iostream>
using namespace std;

tagExplorer::tagExplorer(QWidget *parent)
    : QDialog(parent)
{
    ui.setupUi(this);
//    new QListWidgetItem("Vetti", ui.lstFiles);
//    new QListWidgetItem("Kuppai", ui.lstFiles);

    setAcceptDrops(true);

    whichfile=NULL;
    reListDirs();
    hst = new docHistory();
    ui.txtLocation->setText(tr("/"));

    dowork();
    updatebuttons();

}

tagExplorer::~tagExplorer()
{

}

void tagExplorer::on_btnGo_clicked() {
    dowork();
}

void tagExplorer::reListDirs() {
    ui.lstDirs->clear();
    ui.txtLocation->setFocus();
    linkedlist *lst;
    //printf("\nThis is first call");
    lst=clientgetslashlist(); 
    //printf("\nthis is after");
    ui.lstDirs->setRootIsDecorated(true);
    //ui.lstDirs->setColumnCount(2);
    QTreeWidgetItem *root = new QTreeWidgetItem(ui.lstDirs);
    root->setText(0,tr("/"));
    root->setText(1,tr("/"));
    //ui.lstDirs->setFirstItemColumnSpanned(root, true);
    
    char dir[300];
    char *result;
    char pathsofar[300];
    QTreeWidgetItem *tmpitem;
    QTreeWidgetItem *curparent;
    while (!((lst==NULL) || (lst->isEmpty()))) {
        curparent=root;
        strcpy(pathsofar,"/");
        strcpy(dir,lst->remove());
        result=strtok(dir,"/");
        while (result !=NULL) {
            strcat(pathsofar,result);
            QList<QTreeWidgetItem*> items = ui.lstDirs->findItems(tr(pathsofar), Qt::MatchExactly | Qt::MatchRecursive, 0);
            //printf("\npathsofar: %s", pathsofar);
            if (items.empty()) {
                //printf(" ... not found");
                tmpitem=new QTreeWidgetItem(curparent);
                tmpitem->setText(0,tr(result));
                tmpitem->setText(0,tr(pathsofar));
                tmpitem->setText(1,tr(result));
                tmpitem->setText(1,tr(pathsofar));
        //        ui.lstDirs->setFirstItemColumnSpanned(tmpitem, true);
            } else 
                tmpitem=items.first();
            items.clear();
            curparent=tmpitem;
            result=strtok(NULL,"/");
            strcat(pathsofar,"/");
        }
    }
}

void tagExplorer::updatebuttons() {
    ui.btnBack->setEnabled(hst->isBack());
    ui.btnForward->setEnabled(hst->isForward());
    ui.btnUp->setEnabled((strcmp(hst->getCurrent(),"/")!=0));
}


void tagExplorer::on_btnBack_clicked() {
    if (hst->isBack()) {
        ui.txtLocation->setText(hst->getBack());
        dowork();
    }
}
void tagExplorer::on_btnForward_clicked() {
    if (hst->isForward()) {
        ui.txtLocation->setText(hst->getForward());
        dowork();
    }

}
void tagExplorer::on_btnRefresh_clicked() {
    // Refresh Directory List
   reListDirs();
   // Refresh Files in Current Directory
   dowork();
    
}
void tagExplorer::on_btnUp_clicked(){
       QString st;
       if ((hst!=NULL) && ((hst->getCurrent())!=NULL)) {
           st = hst->getCurrent();
           st.append("/../");
           st=getabsmod((st.toAscii()).data());
           if (st.length()==0)
           st=QString("/");
           ui.txtLocation->setText(st);
           dowork();
       }    
}


void tagExplorer::dowork() {

    if ((ui.txtLocation->text()).length()==0)
        return;
   
    hst->add(ui.txtLocation->text().toAscii().data());
    updatebuttons();
    timetaken = QTime(0,0);
    timetaken.restart();
    QString qst;
    int count;
    qst.fromAscii("Query:");
    linkedlist *fileslist;
    ui.lstFiles->clear();
    fileslist=clientlistfiles(ui.txtLocation->text().toAscii().data());
    count=0;
    if (fileslist!=NULL)
    count=fileslist->count();
    while(! ( ( fileslist!=NULL)  && (fileslist->isEmpty())))
        new QListWidgetItem(QIcon(QString::fromUtf8(":Icons/images/Folder.png")),fileslist->remove(), ui.lstFiles);
   
    QString qst1,qst2;
    qst1=QString::fromAscii("Files Found : ");
    qst2.setNum(count,10);
    qst1.append(qst2);
    ui.lblStatus->setText(qst1);
    qst2.setNum(timetaken.elapsed(),10); 
    qst1=QString::fromAscii("Time Taken : ");  
    qst1.append(qst2);
    qst1.append(QString(" msec(s)"));
    ui.lblTime->setText(qst1);
    QList<QTreeWidgetItem*> items = ui.lstDirs->findItems(ui.txtLocation->text(), Qt::MatchExactly | Qt::MatchRecursive,1);
    if(!items.isEmpty()) ui.lstDirs->setCurrentItem(items.first()); // Make the item visible
    items.clear();    
}

void tagExplorer::on_lstFiles_customContextMenuRequested(QPoint p) {
//    QPoint pos=QPoint(ui.lstFiles->pos());
    selectlist = new linkedlist();
    QList<QListWidgetItem*> sel=ui.lstFiles->selectedItems();
    // no Context Sensitive menu if no item is selected
    if (sel.empty())
        return;

    QList<QListWidgetItem*>::iterator it;
    for(it=sel.begin();it!=sel.end();++it)
        selectlist->add((*it)->text().toAscii().data());
    QMenu *context= new QMenu(this);

    if (sel.count()==1)   {       
        char *st=strdup(selectlist->remove());
        selectlist->add(st);
        if (whichfile!=NULL)
            free(whichfile);
        whichfile=strdup(st);
        context->addAction("&Open", this, SLOT( runfile () ) );
    }
    context->addAction("&Tag", this, SLOT( tag()));
    context->addAction("&Copy To", this, SLOT( copyto()));
    context->addAction("&Move To", this, SLOT( moveto()));
    context->popup(QCursor::pos(),0);
}

void tagExplorer::copyto() {
    Action act = COPYTO;
    perform(act);
}

void tagExplorer::moveto() {
    Action act = MOVETO;
    perform(act);
}

void tagExplorer::perform(int act) {
    //BrowseFolder fold = new BrowseFolder;
    BrowseFolder fold;
    fold.show();
    fold.exec();
    linkedlist *s;
    linkedlist *onlynewtag,*onlyoldtag;
    onlyoldtag=new linkedlist();
    onlynewtag = new linkedlist();
    //onlytag->add(fold.getFolder().toAscii().data());
    //onlytag->add( ui.txtLocation->text().toAscii().data());
    if(fold.result()==Accepted) {
        switch (act) {
            case MOVETO:
		onlyoldtag->add( ui.txtLocation->text().toAscii().data());    
                s=selectlist->copyList();
                while((s!=NULL)&&(!s->isEmpty())) 
		{
		    //printf("%s",s->getdata());
		    //if(strcmp(s->getdata(),"")!=0)
                    clientremovetags(s->remove(),onlyoldtag);
		}
                // break;  -- Dont break as we need to addtags
            case COPYTO:
		onlynewtag->add(fold.getFolder().toAscii().data());
                s=selectlist->copyList();
                while((s!=NULL)&&(!s->isEmpty())) 
                    clientaddtags(s->remove(),onlynewtag);
                break;
            default:
                //Unknown Action!!
                ;
        }
        dowork();
    }
    onlyoldtag->removeAll();
    delete onlyoldtag;
    onlynewtag->removeAll();
    delete onlynewtag;
}

void tagExplorer::runfile() {
    char *params[4];
    params[0]=strdup("kfmclient");
    params[1]=strdup("exec");
    params[2]=strdup(whichfile);
    params[3]=(char*)0;
    int ret;
    pid_t PID;
    PID = fork();
    if (PID == 0) {
       ret = execl ("/usr/bin/kfmclient", "kfmclient","exec",strdup(whichfile),(char*)0);
       return;  //never comes to this
    } 
    for (int i=0;i<3;i++)
    if (params[i]!=NULL)
        free(params[i]);
}

void tagExplorer::openfolder() {
    char *tmp;
    tmp = (char*)malloc(sizeof(char[strlen(whichfile)+5]));
    if(tmp==NULL) {
        return;
    } 
    strcpy(tmp,whichfile);
    strcat(tmp,"/../");
    free(whichfile);
    whichfile=getabsmod(tmp);
    runfile();
    free(tmp);  
}

void tagExplorer::tag() {
    TagEditor *tageditor = new TagEditor;
    linkedlist *lst = new linkedlist();
    lst=selectlist->copyList();
       tageditor->setFileName(lst);
       tageditor->exec();
       lst->removeAll();
       delete lst;
    
    // Refresh Directory List
    reListDirs();
    // Refresh Files in Current Directory
    dowork();
}

void tagExplorer::on_lstDirs_itemDoubleClicked(QTreeWidgetItem *item,int col) {
    if (item!=NULL) {
        ui.txtLocation->setText(item->text(col));
        dowork();
    }
}

void tagExplorer::on_lstFiles_itemDoubleClicked(QListWidgetItem *item) {
    char *name=strdup(item->text().toAscii().data());
    if (whichfile!=NULL)
        free(whichfile);
    whichfile=name;
    runfile();
}


void tagExplorer::dragEnterEvent(QDragEnterEvent *event)
{
    // accept just text/uri-list mime format
    if(event->mimeData()->hasFormat("text/uri-list"))
        event->acceptProposedAction();
}


void tagExplorer::dropEvent(QDropEvent *event)
{
    QList<QUrl> urlList;
    char *fName, *urlName;
    QFileInfo fInfo;

    linkedlist *onlytag;
    onlytag=new linkedlist();
    onlytag->add(ui.txtLocation->text().toAscii().data());


    if (event->mimeData()->hasUrls())
    {
        urlList = event->mimeData()->urls(); // returns list of QUrls
        // if just text was dropped, urlList is empty (size == 0)

        foreach(QUrl url, urlList)
        {
            if(url.isEmpty())
		continue;

            fName = strdup(url.toLocalFile().toAscii().data());
            urlName = strdup(url.toString().toAscii().data());
            fInfo.setFile(fName);
            if(fInfo.isFile())
            {
                qDebug("File dropped? %s\n",fName);
                clientaddtags(fName, onlytag);
		autotag(fName);
            }
            else
            {
                qDebug("URL dropped? %s\n", urlName);
                clientaddtags(urlName, onlytag);
            }
        }
    }

    onlytag->removeAll();
    delete onlytag;

    free(fName);
    free(urlName);
    
    event->acceptProposedAction();
}

*/
void tagExplorer::copyto() {
    Action act = COPYTO;
    perform(act);
}

void tagExplorer::moveto() {
    Action act = MOVETO;
    perform(act);
}

void tagExplorer::perform(int act) {
    //BrowseFolder fold = new BrowseFolder;
    BrowseFolder fold;
    fold.show();
    fold.exec();
    linkedlist *s;
    linkedlist *onlynewtag,*onlyoldtag;
    onlyoldtag=new linkedlist();
    onlynewtag = new linkedlist();
    //onlytag->add(fold.getFolder().toAscii().data());
    //onlytag->add( ui.txtLocation->text().toAscii().data());
    if(fold.result()==Accepted) {
        switch (act) {
            case MOVETO:
		onlyoldtag->add( ui.txtLocation->text().toAscii().data());    
                s=selectlist->copyList();
                while((s!=NULL)&&(!s->isEmpty())) 
		{
		    //printf("%s",s->getdata());
		    //if(strcmp(s->getdata(),"")!=0)
                    clientremovetags(s->remove(),onlyoldtag);
		}
                // break;  -- Dont break as we need to addtags
            case COPYTO:
		onlynewtag->add(fold.getFolder().toAscii().data());
                s=selectlist->copyList();
                while((s!=NULL)&&(!s->isEmpty())) 
                    clientaddtags(s->remove(),onlynewtag);
                break;
            default:
                //Unknown Action!!
                ;
        }
        dowork();
    }
    onlyoldtag->removeAll();
    delete onlyoldtag;
    onlynewtag->removeAll();
    delete onlynewtag;
}

void tagExplorer::runfile() {
    char *params[4];
    params[0]=strdup("kfmclient");
    params[1]=strdup("exec");
    params[2]=strdup(whichfile);
    params[3]=(char*)0;
    int ret;
    pid_t PID;
    PID = fork();
    if (PID == 0) {
       ret = execl ("/usr/bin/kfmclient", "kfmclient","exec",strdup(whichfile),(char*)0);
       return;  //never comes to this
    } 
    for (int i=0;i<3;i++)
    if (params[i]!=NULL)
        free(params[i]);
}

void tagExplorer::openfolder() {
    char *tmp;
    tmp = (char*)malloc(sizeof(char[strlen(whichfile)+5]));
    if(tmp==NULL) {
        return;
    } 
    strcpy(tmp,whichfile);
    strcat(tmp,"/../");
    free(whichfile);
    whichfile=getabsmod(tmp);
    runfile();
    free(tmp);  
}

void tagExplorer::tag() {
    TagEditor *tageditor = new TagEditor;
    linkedlist *lst = new linkedlist();
    lst=selectlist->copyList();
       tageditor->setFileName(lst);
       tageditor->exec();
       lst->removeAll();
       delete lst;
    
    // Refresh Directory List
    reListDirs();
    // Refresh Files in Current Directory
    dowork();
}

void tagExplorer::on_lstDirs_itemDoubleClicked(QTreeWidgetItem *item,int col) {
    if (item!=NULL) {
        ui.txtLocation->setText(item->text(col));
        dowork();
    }
}

void tagExplorer::on_lstFiles_itemDoubleClicked(QListWidgetItem *item) {
    char *name=strdup(item->text().toAscii().data());
    if (whichfile!=NULL)
        free(whichfile);
    whichfile=name;
    runfile();
}


void tagExplorer::dragEnterEvent(QDragEnterEvent *event)
{
    // accept just text/uri-list mime format
    if(event->mimeData()->hasFormat("text/uri-list"))
        event->acceptProposedAction();
}


void tagExplorer::dropEvent(QDropEvent *event)
{
    QList<QUrl> urlList;
    char *fName, *urlName;
    QFileInfo fInfo;

    linkedlist *onlytag;
    onlytag=new linkedlist();
    onlytag->add(ui.txtLocation->text().toAscii().data());


    if (event->mimeData()->hasUrls())
    {
        urlList = event->mimeData()->urls(); // returns list of QUrls
        // if just text was dropped, urlList is empty (size == 0)

        foreach(QUrl url, urlList)
        {
            if(url.isEmpty())
		continue;

            fName = strdup(url.toLocalFile().toAscii().data());
            urlName = strdup(url.toString().toAscii().data());
            fInfo.setFile(fName);
            if(fInfo.isFile())
            {
                qDebug("File dropped? %s\n",fName);
                clientaddtags(fName, onlytag);
		autotag(fName);
            }
            else
            {
                qDebug("URL dropped? %s\n", urlName);
                clientaddtags(urlName, onlytag);
            }
        }
    }

    onlytag->removeAll();
    delete onlytag;

    free(fName);
    free(urlName);
    
    event->acceptProposedAction();
}


